export default {
  data() {
    return {
      newCode: '', // 输入的新股票代码
      stocks: [],   // 默认空列表
      openid:'',
      searchResults: []
    };
  },
  //页面开始加载的动作
  onLoad() {
    this.openid = uni.getStorageSync("openid");
    uni.request({
        url:`https://${this.$IP}:8443/api/wechat/data`,
        data:{openid:this.openid},
        method:'GET',
        success: (resp) => {
          if(resp.data.codes){
              const codes = JSON.parse(resp.data.codes)
              if(codes && codes.length>0){
                for (const code of codes) {
                    console.log(code)
                    this.stocks.push({
                      code: code,
                      name: '加载中',
                      currentPrice: 0,
                      volume: 0,
                      kline: { '5m': null, '30m': null, '60m': null }
                    });
                    this.fetchAllData()
                }
              }else{console.log("no data")}
          }else{
            console.log(resp.data)
          }
        }
      })

  },
  //页面被销毁时动作
  onUnload() {
    clearInterval(this.intervalId);
    const codes = this.stocks.map(item => item.code);
      const codesStr = JSON.stringify(codes);
      uni.request({
        url:`https://${this.$IP}:8443/api/wechat/dataupdate`,
        data:{openid:this.openid,codes:codesStr},
        method:'POST',
        header: {'content-type': 'application/json'},
      })
      console.log("put data")
  },
  onHide() {
    clearInterval(this.intervalId);
  },
  onShow() {
    this.intervalId = setInterval(this.fetchAllData, 1000); // 每1秒刷新
  },
  methods: {
    async fetchAllData() {
      if (this.stocks.length === 0) return; // 没有股票就不请求
      for (let stock of this.stocks) {
        try {
          // 获取实时价格和成交量
          const realRes = await uni.request({
            url: 'https://push2.eastmoney.com/api/qt/stock/get',
            data: { secid: `${stock.code}`, fields: 'f43,f84,f58' }, // f58 = 股票名称
            method: 'GET'
          });
          const realData = realRes.data?.data;
          if (realData && realData !== 'null' && Object.keys(realData).length > 0) {
            console.log(realData);
            stock.currentPrice = realData.f43;
            stock.volume = realData.f84;
            stock.name = realData.f58 || stock.name;
          }else{
            uni.showToast({ title: '没有该股票数据', icon: 'none' });
            this.stocks.pop();
          }
          // 获取 K 线数据
        } catch (err) {
          console.error('获取股票数据失败', err);
        }
      }
      this.stocks = [...this.stocks]; // 触发视图更新
    },

    // 添加新股票
    addStock() {
      if (!this.newCode) return;
       // 判断市场类型
      if (this.newCode.startsWith('6')) {
        this.newCode = '1.'+this.newCode; // 沪市
      } else if (this.newCode.startsWith('0') || this.newCode.startsWith('3')) {
        this.newCode = '0.'+this.newCode
      } else {
        uni.showToast({ title: '无效的股票代码', icon: 'none' });
        return;
      }
      //判断新添加的股票是否重复
      const isDuplicate = this.stocks.some(stock => stock.code === this.newCode);
      if (isDuplicate) {
        uni.showToast({ title: '该股票已在列表中', icon: 'none' });
        this.newCode = '';
        return
      } 

      this.stocks.push({
        code: this.newCode,
        name: '加载中',
        currentPrice: 0,
        volume: 0,
        kline: { '5m': null, '30m': null, '60m': null }
      });
      this.newCode = '';
      this.fetchAllData(); // 立即拉取新股票的数据
    },

    gp_data(code){
      console.log(code);
      uni.navigateTo({url: `/pages/data/gpdata?code=${code}`});
    },
    removeStock(index) {
       uni.showModal({
          title: '提示',
          content: '确定删除该股票吗？',
          cancelText: '取消',
          confirmText: '删除',
          success: (res) => {
            if (res.confirm) {
              this.stocks.splice(index, 1);
              this.stocks = [...this.stocks]; // 确保视图更新
            }
          }
        });
    },
    //实时获取股票号码
    onInputChange(e){
      const name = e.detail.value;
      uni.request({
        url:'https://search-codetable.eastmoney.com/codetable/search/web',
        data:{keyword:name,pageIndex:"1",pageSize:"10"},
        method:"GET",
        success:(res)=>{
          const list = res.data.result || [];
          this.searchResults = list.map(item =>({code:item.code,name:item.shortName}))
        }
      })
    },
    selectStock(item) {
      this.newCode = item.code;   // 选中后填到输入框
      this.searchResults = [];    // 清空下拉菜单
      this.addStock()
    },
  }
};